from json import loads, dumps
from time import time
from common import make_verify_sign
from config import PROXY_RDS_KEY
from log import err, out
from requests import post


class CommandBase:

    def __init__(self, bs, param):
        self.command_params = param
        if isinstance(self.command_params, dict):
            self.__dict__.update(self.command_params)

        self.bs = bs
        self.chrome = self.bs.chrome
        self.chrome.alert_ok()

    def send(self, url, **data):
        data.pop('indx', None)
        data['uuid'] = self.bs.center_uuid
        data['times'] = int(time())
        data['sign'] = make_verify_sign(data, None, 'QrCodeTask', self.bs.center_key)
        try:
            out(url, data)
            r = post(url, data)
            out('Send Response: ', r.text)
            if r.text == 'SUCCESS':
                return 'Yes'
            return loads(r.text).get('code')
        except Exception as e:
            err('API接口发送错误: ' % e, stack=True)

        return None

    def window_init(self):
        """
        保证浏览器唯一标签
        """
        d = self.chrome
        num = len(d.window_handles)
        while num > 1:
            num = num - 1
            d.switch_to_window(d.window_handles[num])
            d.close()
        d.switch_to_window(d.window_handles[0])

    def check_proxy_expire(self):
        """
        检测代理IP是否过期, 过期重启浏览器
        """
        if (self.chrome.get_proxy_server() is None
                or self.bs.rds.get(PROXY_RDS_KEY)):
            return False
        self.chrome.quit()
        self.chrome.driver = self.chrome.open()
        self.center.client = None
        return True

    def check_chrome(self):
        """
        检测浏览器是否在线
        """
        #  检查浏览器是否存在
        if not self.chrome.reachable():
            #  不存在重启浏览器
            self.chrome.driver = self.chrome.open()
            return False
        #  self.window_init()
        self.chrome.switch_to_window(self.chrome.window_handles[0])
        return True

    def start(self):
        """
        任务执行入口
        """
        out('Command Start(%s): %s' % (self, self.command_params))

        #  判断浏览器是否存在
        unchecklist = ['online', 'offline']
        if self.cmdname not in unchecklist and not self.check_chrome():
            return self.bs.quit('lost')

        return self.run()

